package rursu.view;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import rursu.business.MovieApplication;
import rursu.business.R;
import rursu.business.pojo.Movie;
import rursu.business.pojo.MovieDetails;
import rursu.business.pojo.MovieImage;
import rursu.business.pojo.Person;
import rursu.providers.callback.ImageLoaderCallback;
import rursu.providers.callback.MovieDetailsCallback;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

public class MovieDetailsFragment extends Fragment implements MovieDetailsCallback, ImageLoaderCallback { 
	
	private final String LOGGER_TAG = this.getClass().getCanonicalName();
	private int numOfScreenShotsPerLine;
	private Movie movie;
	private List<ImageView> screenshots = new ArrayList<ImageView>();
	private MovieDetails details;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {				
		
		View view = inflater.inflate(R.layout.details_layout, container, false);
		
		numOfScreenShotsPerLine = getResources().getInteger(R.integer.movie_screen_shot_number);
		
		((MovieApplication)getActivity().getApplication()).getDataProviderManager().getMovieDetails(movie, this);
		((MovieApplication)getActivity().getApplication()).getImageProviderManager().stopLoading();
		return view;
	}	

	
	public void onDataDownloaded(MovieDetails details) {
		
		if ( !this.isVisible() ) {
			return;
		}
		
		this.details = details;
		
		Log.v(LOGGER_TAG, "Details data for " + details.getName() + " downloaded");
		View view = getView();	
		
		// inflating film name
		TextView filmName = (TextView) view.findViewById(R.id.film_name);
		filmName.setText(details.getName());
		
		// inflating release date
		TextView releaseDate = (TextView) view.findViewById(R.id.release_date);
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

		Date date = null;
		try {
			date = formatter.parse(details.getReleased());
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		if (date != null){
			formatter = new SimpleDateFormat("MMMM dd, yyyy");
			releaseDate.setText(formatter.format(date).toString());
		}
		
		
		// inflating cast
		TextView cast = (TextView) view.findViewById(R.id.cast);
		
		StringBuilder persons = new StringBuilder();
		
		for (Person person : details.getCast()) {
			persons.append(person.getName() + ", ");
		}
		// delete redundant ','
		
		if (persons.length() >= 2) {
			persons.delete(persons.length() - 2, persons.length() - 1);
		}
		
		cast.setText(persons.toString());
		
		// inflating description
		TextView description = (TextView) view.findViewById(R.id.movie_description);
		description.setText(details.getOverview());
		
		RatingBar ratingBar = (RatingBar) view.findViewById(R.id.details_fan_rating);
		ratingBar.setRating(details.getRating());
		
		// do layout
		view.invalidate();
		
		
		((MovieApplication)getActivity().getApplication()).getImageProviderManager().getPoster(details, this);
	}



	public synchronized void onImageLoaded(MovieImage image) {

		Log.v(LOGGER_TAG, "Image for " + image.getUrl() + " loaded");
		
		if ( !isVisible() ) {
			return;
		}
		
		if ( image.getType().equals("poster") ) {
			
			ImageView poster = (ImageView) getView().findViewById(R.id.movie_poster);
			
			if ( image.getBitmap() == null ) {
				
				poster.setImageResource( R.drawable.default_film_poster );
			} else {
				poster.setImageBitmap(image.getBitmap());					
			}
			
			((MovieApplication)getActivity().getApplication()).getImageProviderManager().getMovieThumb(details, this);
		}
		
		if (  image.getType().equals("backdrop")  ) {
			
			LinearLayout container = (LinearLayout) getView().findViewById(R.id.screen_shot_container);
			
			// checking whether there are children in main container 
			if (container.getChildCount() > 0) {
				
				// obtain last line
				LinearLayout currentLayout = (LinearLayout) container.getChildAt( container.getChildCount() - 1 );
				
				// checking whether there is free space in last line
				if ( currentLayout.getChildCount() < numOfScreenShotsPerLine ) {						
					
					ImageView imageView = (ImageView) getActivity().getLayoutInflater().inflate(R.layout.details_screen_shot_layout, currentLayout, false);
					
					imageView.setVisibility(View.INVISIBLE);
					screenshots.add(imageView);
					
					if ( image.getBitmap() == null ) {
						imageView.setImageResource(R.drawable.no_screen_shot);
					} else {
						imageView.setImageBitmap(image.getBitmap());
					}
					
					currentLayout.addView(imageView); 
					
				} else {
					// if last line is full, new line will be created
					addImagesToNewLayout(container, image);
				}					
				
			} else {
				// if the main container if empty, the new line will be created
				addImagesToNewLayout(container, image);
			}				
		}

	}

	private void addImagesToNewLayout(LinearLayout container, MovieImage imageContainer) {
		
		LinearLayout newLayout = new LinearLayout(container.getContext());
		container.addView(newLayout);
		
		newLayout.setOrientation(LinearLayout.HORIZONTAL);		
		newLayout.setGravity(Gravity.LEFT);
		newLayout.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
		newLayout.setBackgroundColor(Color.WHITE);
		
		ImageView imageView = (ImageView) getActivity().getLayoutInflater().inflate(R.layout.details_screen_shot_layout, newLayout, false);
		
		if ( imageContainer.getBitmap() == null ) {
			imageView.setImageResource( R.drawable.no_screen_shot );
		} else {
			imageView.setImageBitmap(imageContainer.getBitmap());
		}
		
		imageView.setVisibility(View.INVISIBLE);
		screenshots.add(imageView);
		
		//imageView.setImageBitmap(restriction.getBitmap());
		newLayout.addView(imageView);
	}

	public void onImageLoadCancelled(String reason) {
		// TODO Auto-generated method stub
	}

	public void onDataPreDownload() {
		// TODO Auto-generated method stub
		
	}

	public void onFailure() {
		// TODO Auto-generated method stub
		
	}

	public Movie getMovie() {
		return movie;
	}

	public void setMovie(Movie movie) {
		this.movie = movie;
	}

	public void onImagePreLoad(MovieImage image) {
		// TODO Auto-generated method stub
		
	}


	public void onLoadFinished(int imageNumber) {
		
		if ( isVisible() ) {			
			for (ImageView image : screenshots) {
				image.setVisibility(View.VISIBLE);
			}
			
			this.getView().invalidate();
		}
	}
	
}
